/**
 * CollectionFormatter
 *
 * @author Chris Pratt
 *
 * 11/26/2009
 */
package com.anodyzed.onyx.text;

import com.anodyzed.onyx.util.Convert;

import java.util.Map;

public class CollectionFormatter extends TextFormatter {
  private char delim;
  private int[] fixed;

  /**
   * Constructor
   *  
   * @param parent The parent TextFormat 
   * @param key The Argument Index or Map Key for this node 
   * @param bean The additional Bean reference String 
   */
  public CollectionFormatter (TextFormat parent,CharSequence key,CharSequence bean) {
    super(parent,key,bean);
    delim = ',';
  } //CollectionFormatter

  /**
   * Constructor
   *  
   * @param parent The parent TextFormat 
   * @param key The Argument Index or Map Key for this node 
   * @param bean The additional Bean reference String 
   * @param fmt The Format String 
   */
  public CollectionFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence fmt) {
    super(parent,key,bean);
    if(fmt.length() > 0) {
      String str;
      if(fmt.equals("csv")) {
        delim = ',';
      } else if(fmt.equals("tsv")) {
        delim = '\t';
      } else if(Character.isDigit(fmt.charAt(0)) && ((str = fmt.toString()).indexOf(',') != -1)) {
        int i = 0;
        String[] lens = Convert.toStringArray(str,',');
        fixed = new int[lens.length];
        for(String len : lens) {
          fixed[i++] = Integer.parseInt(len);
        }
      } else {
        delim = fmt.charAt(0);
      }
    }
  } //CollectionFormatter

  /**
   * Return a string representation of an array
   *
   * @param args The Formatting Arguments
   * @return The Formatted String
   */
  @Override
  public String toString (Object... args) {
    Object o = getValue(args);
    if(o != null) {
      if(fixed == null) {
        if(o.getClass().isArray()) {
          return Convert.toDelimitedString((Object[])o,delim);
        } else if(o instanceof Map<?,?>) {
          return Convert.toDelimitedString((Map<?,?>)o,delim);
        } else if(o instanceof Iterable<?>) {
          return Convert.toDelimitedString((Iterable<?>)o,delim);
        } else if(o instanceof String) {
          return (String)o;
        }
      } else {
        if(o.getClass().isArray()) {
          return Convert.toFixedString((Object[])o,fixed);
        } else if(o instanceof Iterable<?>) {
          return Convert.toFixedString((Iterable<?>)o,fixed);
        }
      }
    }
    return null;
  } //toString

} //*CollectionFormatter
